package de.dopichaj.labrador.inex;

import java.io.PrintWriter;

import de.dopichaj.labrador.search.hit.Hit;
import de.dopichaj.labrador.search.hit.HitHierarchyTree;


/**
 * Create context graphs from HitHierarchyTrees.
 */
public class ContextGraphWriter {
    
    private final PrintWriter writer;
    private boolean inGraph = false;
    private int startpos;

    /**
     * 
     * @param writer the writer to write the ploticus file to
     */
    public ContextGraphWriter(PrintWriter writer) {
        this.writer = writer;
    }
    
    /**
     * Start a new graph.
     * 
     * Must be called before calling drawHit.
     * 
     * @param width width of the drawing area in inches
     * @param height
     * @param length the length of the root element
     * @param maxScore the maximum score
     */
    private void startGraph(double width, double height, int startpos, int length, double maxScore) {
        
        this.startpos = startpos;
        
        writer.println("#proc areadef");
        writer.println("location: 1 1");
        writer.println("box " + width + " " + height);
        writer.println("xrange: 0 " + length);
        writer.println("yrange: 0 " + maxScore);
        
        writer.println("#proc xaxis");
        writer.println("label: position");
        writer.println("stubs: inc");

        writer.println("#proc yaxis");
        writer.println("label: score");
        writer.println("stubs: inc");
        writer.println("tics: yes");
        writer.println("ticincrement: 0.1");
        
        inGraph = true;
    }
    
    /**
     * Finish the current graph.
     */
    private void endGraph() {
        writer.println("#proc page");
        
        inGraph = false;
    }
    
    /**
     * Draw a single hit.
     */
    private void drawHit(Hit hit) {
        
        if (!inGraph) {
            throw new IllegalStateException("Trying to call drawHit without having called startGraph");
        }
        
        int pos = hit.getPosition() - startpos;
        int len = hit.getContentLength();
        
        // draw the rectangle
        writer.println("#proc rect");
        writer.println("rectangle: " + pos + "(s) 0(s) " +
            (pos + len) + "(s) " + hit.getScore() + "(s)");
        writer.println("outline: style=0 color=black width=0.1");
        writer.println("color: none");

        // draw the label
        String label = hit.getXPath().replaceFirst(".+/", "//");
        writer.println("#proc annotate");
        writer.println("verttext: yes");
        writer.println("text: " + label + "\n");
        writer.println("location: " + (pos + len) + "(s) " + hit.getScore() + "(s)");
        writer.println("textdetails: align=left adjust=-0.05,0.05");
    }

    /**
     * Draw the given hit (if it is in the result set) and its children.
     */
    private void drawTreeRecursive(HitHierarchyTree tree, Hit hit) {
        
        // draw the hit
        if (tree.isInResults(hit)) {
            drawHit(hit);
        }

        // draw the children
        for (Hit child : tree.getChildren(hit)) {
            drawTreeRecursive(tree, child);
        }
    }

    /**
     * Draw a skyline diagram for the given result tree.
     * @param tree      the tree to print
     * @param maxScore  the maximum score in the tree (used for scaling; if inaccurate,
     *                  drawing may look strange, but is still valid)
     */
    public void drawTree(HitHierarchyTree tree, double width, double height, float maxScore) {
        
        Hit root = tree.getRoot();
        startGraph(width, height, root.getPosition(), root.getContentLength(), maxScore);

        // draw the skyline diagram
        drawTreeRecursive(tree, root);
        
        endGraph();
    }
    
    /**
     * Draw a skyline diagram for the given result tree.
     * @see #drawTree(HitHierarchyTree, double, double, float)
     */
    public void drawTree(HitHierarchyTree tree, double width, double height, float maxScore, String label) {
        
        Hit root = tree.getRoot();
        startGraph(width, height, root.getPosition(), root.getContentLength(), maxScore);
        
        if (!label.equals("")) {
            writer.println("#proc annotate");
            writer.println("text: " + label + "\n");
            writer.println("location: 0(s) 0.4");
            writer.println("textdetails: align=left");
        }
        
        // draw the skyline diagram
        drawTreeRecursive(tree, root);
        
        endGraph();
    }
    
    /**
     * Close the graph.
     * 
     * This also closes the associated PrintWriter.
     */
    public void close() {
        writer.close();
        inGraph = false;
    }
}
/*
Copyright (c) 2007 Philipp Dopichaj

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/